<?php


namespace app\model\base;

use think\Model;

class WeeklyCount extends Model
{

  protected static $targetColumnName = '';

  public static function incCount($target_id, $week_date = null)
  {
    $model_count = self::getCount($target_id, $week_date);

    $model_count->count = $model_count->count + 1;

    $model_count->save();
    return $model_count;
  }


  public static function decCount($target_id, $week_date = null)
  {

    $model_count = self::getCount($target_id, $week_date);

    $model_count->count = $model_count->count - 1;

    $model_count->save();

    return $model_count;
  }

  public static function getCount($target_id, $week_date = null)
  {
    $week_date = self::parseDate($week_date);

    $called_class_name = get_called_class();

    $model_count = $called_class_name::where($called_class_name::$targetColumnName, $target_id)
      ->where('week_date', $week_date)
      ->find();

    if (empty($model_count)) {
      $model_count = $called_class_name::create([
        $called_class_name::$targetColumnName => $target_id,
        'week_date' => $week_date,
        'count' => 0
      ]);
    }


    return $model_count;
  }

  public static function parseDate($week_date = null)
  {
    if (is_null($week_date)) {
      // 本周一
      $week_date = date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600));
    }

    return $week_date;
  }
}
